import ProLayout from '@ant-design/pro-layout';
import React, {useEffect, useRef, useState} from 'react';
import {connect, history, Link, useIntl} from 'umi';
import {BackTop, message} from 'antd';
import RightContent from '@/components/GlobalHeader/RightContent';
import styles from '@/wldos.less';
import { getHome, wldosHeader} from "@/utils/utils";
import Document from "@/pages/doc/components/Document";

const Doc = (props) => {
  const {
    dispatch,
    location = {
      pathname: '/',
    },
    menuData,
    currentDoc,
    currentChapter,
    settings,
    loading,
    site,
    tdk,
  } = props;
  const [seo, setSeo] = useState({title: '', keywords: '', description: '', logo: '', favicon: '', crumbs: []});
  const [collapsed, setCollapsed] = useState(false);

  const queryDoc = (dispatch, callback) => {
    dispatch({
      type: 'docs/fetchDoc',
      payload: {
        current: 1,
        pageSize: 50, // 默认50个文档
        sorter: {"createTime":"ascend"}
      },
      callback,
    });
  };

  const queryCurrentDoc = (dispatch, params, callback) => {
    dispatch({
      type: 'docs/fetchCurrentDoc',
      payload: {
        bookId: params.bookId,
      },
      callback,
    });
  };

  const queryCurrentChapter = (dispatch, params) => {
    dispatch({
      type: 'docs/fetchCurrentChapter',
      payload: {
        bookId: params.bookId,
        chapterId: params.chapterId,
      },
    });
  };

  const callback4Chapter = (dispatch, resp) => {
    if (resp.message === 'ok') {
      const {id: bookId, chapter} = resp.data;
      if (chapter?.length > 0) {
        const {id: chapterId} = chapter[0];
        history.push({
          pathname: `/docs/book/${bookId}/chapter/${chapterId}`,
        });
      } else {
        queryCurrentChapter(dispatch, {bookId, chapterId: ''});
      }
    }
  };

  const query = (dispatch, params, path) => {
    if (path === '/docs/book') {
      queryDoc(dispatch, (res) => {
        const {data: {rows = [],},} = res;
        if (rows?.length > 0) {
          history.push({
            pathname: `/docs/book/${rows[0].id}`,
          });
        }
      });
    } else if (path === '/docs/book/:bookId/chapter/:chapterId') {
      if (menuData.length === 0) {
        queryDoc(dispatch, null);
      }
      if (!currentDoc.id || currentDoc.chapter.length <= 1) {
        queryCurrentDoc(dispatch, params, null);
      }
      queryCurrentChapter(dispatch, params);
    } else { // match '/docs/book/:bookId'
      if (menuData.length === 0) {
        queryDoc(dispatch, null);
      }
      queryCurrentDoc(dispatch, params, (res) => callback4Chapter(dispatch, res), );
    }
  }

  const docClick = (key, props) => {
    const {dispatch, curId, curLen} = props;
    if (curId !== key || curLen <= 1) {
      queryCurrentDoc(dispatch, {bookId: key}, (res) => callback4Chapter(dispatch, res), );
    }
  }

  const menuHandle = (menus, parentId, isChapter, props) =>
    menus.map((item) => ({
      ...item,
      name: item.pubTitle ? (isChapter ? item.pubTitle : <Link onClick={() => docClick(item.id, props)}>{item.pubTitle}</Link>) : '无标题',
      path: isChapter ? `/docs/book/${parentId}/chapter/${item.id}` : `/docs/book/${item.id}`,
      children: item.chapter && menuHandle(item.chapter, item.id, true),
    }));

  const menuDataRef = useRef([]);

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
      dispatch({
        type: 'user/fetchSite',
      });
    }

    // 首次访问，清除docUrl，防止历史数据干扰查询
    localStorage.removeItem('docUrl');
  }, []);

  useEffect(() => {
    const { match: {path, params, url} } = props;
    if (url !== localStorage?.getItem('docUrl') || !currentDoc.id) {
      if (dispatch) {

        query(dispatch, params, path);
        localStorage.setItem('docUrl', url);
      }
    }
  }, [location.pathname]);

  useEffect(async () => {

    const {siteName, siteTitle, siteKeyword, siteDescription, siteLogo, favicon} = site;
    const pageDesc = siteTitle ? ` - ${siteName}` : '';

    // 定义seo标签，首页取默认配置，内容页需要传递
    const homeFlag = location.pathname === getHome();
    setSeo({
      // eslint-disable-next-line no-nested-ternary
      title: homeFlag ? (siteTitle?? '') : (tdk.title ? `${tdk.title}${pageDesc}` : ''),
      keywords: homeFlag ? siteKeyword : tdk.keywords || siteKeyword,
      description: homeFlag ? siteDescription : tdk.description || siteDescription,
      logo: siteLogo,
      favicon,
      crumbs: tdk.crumbs || [],
    });
    // 自动回到顶部
    document?.getElementById('root').scrollIntoView(true);
  }, [tdk]);

  const handleMenuCollapse = (payload) => {
    setCollapsed(payload);
  };

  const {formatMessage} = useIntl();
  return (
    <>
      {wldosHeader(seo)}
      <ProLayout
        className={styles.slideNavWldos}
        logo={seo.logo}
        title={seo.title}
        // formatMessage={formatMessage}
        pageTitleRender = {(titleProps) => {
          return titleProps.title;
        }}
        menuDataRender={(md) => menuHandle(md?.length>0 ? menuData.pushAll(md) : menuData, 0, false, {dispatch, curId: currentDoc.id, curLen: currentDoc?.chapter?.length?? 0})}
        {...settings}
        menu={loading}
        collapsed={collapsed}
        onCollapse={handleMenuCollapse}
        onMenuHeaderClick={() => history.push('/')}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (
            menuItemProps.isUrl ||
            !menuItemProps.path ||
            (location && location.pathname === menuItemProps.path)
          ) {
            return defaultDom;
          }
          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        breadcrumbRender={(routers = []) => [
          { // 自定义面包屑的数据
            path: '/',
            breadcrumbName: formatMessage({
              id: 'menu.home',
            }),
          },
          ...routers,
        ]}
        /* eslint-disable-next-line no-unused-vars */
        itemRender={(route, params, routes, paths) => {
          const last = routes.indexOf(route) === routes.length - 1;
          return last ? (
            <span>{route.breadcrumbName}</span>
          ) : (
            <Link to={route.path}>{route.breadcrumbName}</Link>
          );
        }}
        menuHeaderRender={(lgo/* , title */) => {
          if (!seo.logo) { return ''; }
          return lgo;
        }}
        rightContentRender={() => <RightContent />}
        postMenuData={(menu) => {
          menuDataRef.current = menu || [];
          return menu || [];
        }}
        siderWidth={300}
      >
        <Document key={currentChapter.id} {...{currentChapter, dispatch}}/>
      </ProLayout>
      <BackTop/>
    </>
  );
};

export default connect(({settings, docs, user, loading}) => ({
  tdk: user.tdk,
  site: user.site,
  menuData: docs.doc,
  currentDoc: docs.currentDoc,
  currentChapter: docs.currentChapter,
  loading: loading.models.user,
  settings: {
    ...settings,
    layout: "side",
    contentWidth: "Fluid",
    headerHeight: 48,
  }
}))(Doc);
